package com.zoweunion.mechanic.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.app.OrderService;
import com.zoweunion.mechanic.util.UuidUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AppService appService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询仓库位置
     */
    @PostMapping("deleteWarehouseLocation")
    public Object deleteWarehouseLocation(@RequestBody String string, HttpServletRequest request) throws Exception {

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        reqMap.put("s_id",getCurrentUser(request).getS_id());

        orderService.deleteWarehouseLocation(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 查询仓库位置
     */
    @PostMapping("getWarehouseLocation")
    public Object getWarehouseLocation(@RequestBody String string, HttpServletRequest request) throws Exception {

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        reqMap.put("s_id",getCurrentUser(request).getS_id());

        List<Map<String, Object>> result = orderService.getWarehouseLocation(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
    }

    /**
     * 保存仓库位置
     */
    @PostMapping("savaWarehouseLocation")
    public Object savaWarehouseLocation(@RequestBody String string, HttpServletRequest request) throws Exception {

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        reqMap.put("user_id",getCurrentUser(request).getId());

        reqMap.put("s_id",getCurrentUser(request).getS_id());

        orderService.savaWarehouseLocation(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 修工完成维修
     */
    @PostMapping("repairComplete")
    public Object repairComplete(@RequestBody String string, HttpServletRequest request) throws Exception {

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        reqMap.put("id",getCurrentUser(request).getId());

        reqMap.put("repair_id",getCurrentUser(request).getId());

        Map<String, Object> resultMap = orderService.repairComplete(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }

    /**
     * 修工互检
     */
    @PostMapping("repairMutualCheck")
    public Object repairMutualCheck(@RequestBody String string, HttpServletRequest request) throws Exception {

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        User currentUser = getCurrentUser(request);
        reqMap.put("id", currentUser.getId());
        reqMap.put("user_name",currentUser.getUser_name());
        reqMap.put("s_id",currentUser.getS_id());

        reqMap.put("repair_id", currentUser.getId());

        Map<String, Object> resultMap = orderService.repairMutualCheck(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }

    /**
     * 修工自检
     */
    @PostMapping("repairSelfCheck")
    public Object repairSelfCheck(@RequestBody String string, HttpServletRequest request) throws Exception {

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        User currentUser = getCurrentUser(request);
        reqMap.put("id", currentUser.getId());
        reqMap.put("user_name", currentUser.getUser_name());
        reqMap.put("repair_id", currentUser.getId());
        reqMap.put("s_id", currentUser.getS_id());

        boolean bool = orderService.repairSelfCheck(reqMap);

        if (bool) {

            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
        }else {

            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
        }
    }

    /**
     * 转诊
     */
    @PostMapping("changeDiagnoseInfo")
    public Object changeDiagnoseInfo(@RequestBody String string, HttpServletRequest request) throws Exception {

        logBefore(logger, "转诊");

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        User currentUser = getCurrentUser(request);

        reqMap.put("user_id",currentUser.getId());
        reqMap.put("r_id",currentUser.getR_id());

        Boolean bool = orderService.changeDiagnoseInfo(reqMap);

        if (bool == true) {

            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
        }else {

            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
        }
    }

    /**
     * 更新听诊信息
     */
    @PostMapping("updateDiagnoseInfo")
    public Object updateDiagnoseInfo(@RequestBody String string, HttpServletRequest request) throws Exception {

        logBefore(logger, "更新听诊信息");

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        User currentUser = getCurrentUser(request);

        reqMap.put("user_id",currentUser.getId());
        reqMap.put("r_id",currentUser.getR_id());

        Boolean bool = orderService.updateDiagnoseInfo(reqMap);

        if (bool == true) {

            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
        }else {

            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
        }
    }

    /**
     * 获取工单详情
     */
    @PostMapping("getOrderDetail")
    public Object getOrderDetail(@RequestBody String string, HttpServletRequest request) throws Exception {

        logBefore(logger, "获取工单详情");

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        User currentUser = getCurrentUser(request);

        reqMap.put("user_id",currentUser.getId());
        reqMap.put("r_id",currentUser.getR_id());

        Map<String, Object> orderDetail = orderService.getOrderDetail(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", orderDetail);
    }

    /**
     * 获取工单列表
     */
    @PostMapping("getOrderList")
    public Object getOrderList(@RequestBody String string, HttpServletRequest request) throws Exception {

        logBefore(logger, "获取工单列表");

        User currentUser = getCurrentUser(request);

        Map<String,Object> reqMap = JSONObject.parseObject(string, Map.class);

        reqMap.put("r_id",currentUser.getR_id());
        reqMap.put("user_id",currentUser.getId());
        reqMap.put("s_id",currentUser.getS_id());

        // 获取当前用户的管辖区域
        if (Constants.ROLE_KF.equals(currentUser.getR_id()) || Constants.ROLE_GG.equals(currentUser.getR_id()) || Constants.ROLE_GLY.equals(currentUser.getR_id())) {
            reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(currentUser.getId(), currentUser.getS_id())));
        }

        List<Map<String,Object>> orderList = orderService.getOrderList(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", orderList);
    }

    /**
     * 高管优惠金额
     */
    @PostMapping("privilegeMoney")
    public Object privilegeMoney(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

        String userId = getCurrentUser(request).getId();

        reqMap.put("userId",userId);

        JSONObject resultObj = new JSONObject();
        int code = Constants.CODE_ERROR;
        String message = "";

        try {

            String money = orderService.getManagerPrivilegeMoney(reqMap);

            if (money.length() != 0) {

                Map<String,Object> map = new HashMap<>();

                map.put("privilegeMoney",money);
                resultObj.put("data",map);

                code = Constants.CODE_SUCCESS;
                message = "操作成功";
            }else {

                code = Constants.CODE_ERROR;
                message = "该账号没有工单改价授权";
            }

        } catch (Exception e) {

            code = Constants.CODE_ERROR;
            message = "操作失败";
            logger.error(e.toString(), e);

        } finally {

            resultObj.put("code", code);
            resultObj.put("message", message);
            logAfter(logger);
        }

        return resultObj;
    }

    /**
     * 高管改价
     */
    @PostMapping("changePrivilegeMoney")
    public Object changePrivilegeMoney(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

        String userId = getCurrentUser(request).getId();

        reqMap.put("userId",userId);

        JSONObject resultObj = new JSONObject();
        int code = Constants.CODE_ERROR;
        String message = "";

        try {

            Boolean authFlag = orderService.queryManagerPrivilegeAuth(reqMap);

            if (authFlag) {

                Boolean result = orderService.updateAuthPrice(reqMap);

                if (result) {

                    code = Constants.CODE_SUCCESS;
                    message = "操作成功";
                }else {

                    code = Constants.CODE_ERROR;
                    message = "操作失败";
                }

            }else {

                code = Constants.CODE_ERROR;
                message = "工单改价授权密码错误";
            }

        } catch (Exception e) {

            code = Constants.CODE_ERROR;
            message = "操作失败";
            logger.error(e.toString(), e);

        } finally {

            resultObj.put("code", code);
            resultObj.put("message", message);
            logAfter(logger);
        }

        return resultObj;
    }

    /**
     * 记录修工的出发记录，修工点领料的时候调取
     */
    @PostMapping("repairLocationRecord")
    public Object repairLocationRecord(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        logBefore(logger, "记录修工的出发记录");

        User currentUser = getCurrentUser(request);

        Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);

        reqMap.put("s_id",currentUser.getS_id());
        reqMap.put("user_id",currentUser.getId());

        orderService.repairLocationRecord(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 工单支付
     */
    @PostMapping("orderPay")
    public Object orderPay(@RequestBody String str, HttpServletRequest request)
            throws Exception {

//        order_id: this.order_no,
//                s_id: this.obj.s_id,
//                order_status: 17,
//                payment_status: 2,
//                payment_type: 1,
//                payment_amount: this.price,
//                u_id: this.u_id
//    };

        logBefore(logger, "工单支付");

        User currentUser = getCurrentUser(request);

        Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);

        reqMap.put("user_id",currentUser.getId());

        orderService.orderPay(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 修工到达现场
     */
    @PostMapping("orderRepairArrive")
    public Object orderRepairArrive(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        logBefore(logger, "修工到达现场");

        User currentUser = getCurrentUser(request);

        Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);

        reqMap.put("user_id",currentUser.getId());
        reqMap.put("s_id",currentUser.getS_id());

        orderService.orderRepairArrive(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 信用额度的还款
     */
    @PostMapping("creditLimitRepayment")
    public Object creditLimitRepayment(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        logBefore(logger, "信用额度的还款");

        User currentUser = getCurrentUser(request);

        Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);

        reqMap.put("user_id",currentUser.getId());
        reqMap.put("s_id",currentUser.getS_id());
        reqMap.put("id", UuidUtil.get32UUID());

        orderService.creditLimitRepayment(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 信用额度的还款
     */
    @PostMapping("creditLimitDetail")
    public Object creditLimitDetail(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        logBefore(logger, "信用额度使用详情");

        User currentUser = getCurrentUser(request);

        Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);

        reqMap.put("user_id",currentUser.getId());
        reqMap.put("s_id",currentUser.getS_id());

        Map<String,Object> creditLimitDetailMap = orderService.creditLimitDetail(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", creditLimitDetailMap);
    }

    @GetMapping("/selectOrderCheckUser")
    public ResponseBean selectOrderCheckUser(@RequestParam Map<String, Object> params,  HttpServletRequest request) throws Exception {
        params.put("s_id",getCurrentUser(request).getS_id());
        List<Map<String, Object>>  checkCount = orderService.selectOrderCheckUser(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }

    @GetMapping("/selectOrderCheck")
    public ResponseBean selectOrderCheck(@RequestParam Map<String, Object> params,  HttpServletRequest request) throws Exception {
        User currentUser = getCurrentUser(request);
        params.put("s_id",currentUser.getS_id());
        Map<String, Object>  checkCount = orderService.selectByOrderCheck(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }


    /**
     * 客服响应统计
     * @param params
     * @return
     * @throws Exception
     */
    @GetMapping("/selectResponseByKf")
    public ResponseBean selectResponseByKf(@RequestParam Map<String, Object> params,  HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        List<Map<String, Object>> checkCount = orderService.selectResponseByKf(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }

    /**
     * 配件单数占比
     * @param params
     * @returnc
     * @throws Exception
     */
    @GetMapping("/selectCorrectPer")
    public ResponseBean selectCorrectPer(@RequestParam Map<String, Object> params,  HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        List<Map<String, Object>> checkCount = orderService.selectCorrectPer(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }


    /**
     * 支付方式占比
     * @param params
     * @return
     * @throws Exception
     */
    @GetMapping("/selectPayGroup")
    public ResponseBean selectPayGroup(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        Map<String, Object> checkCount = orderService.selectPayGroup(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }

    /**
     * 修工完成工单用时
     * @param params
     * @return
     * @throws Exception
     */
    @GetMapping("/selectRepairTime")
    public ResponseBean selectRepairTime(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        List<Map<String, Object>> checkCount = orderService.selectRepairTime(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }

    /**
     * 配件当天入库
     * @param params
     * @return
     * @throws Exception
     */
    @GetMapping("/selectPartsInCount")
    public ResponseBean selectPartsInCount(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        List<Map<String, Object>> checkCount = orderService.selectPartsInCount(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }

    /**
     * 故障类型统计
     * @param params
     * @return
     * @throws Exception
     */
    @GetMapping("/selectFaultCount")
    public ResponseBean selectFaultCount(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        List<Map<String, Object>> checkCount = orderService.selectFaultCount(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",checkCount );
    }

    /**
     *  tdo 绩效统计列表
     */
    @GetMapping("/selectCheckList")
    public ResponseBean selectCheckList(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        params.put("sId",getCurrentUser(request).getS_id());
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功",
                orderService.selectCheckList(params));
    }

}
